const g = require("../utils/constants");

cc.Class({
    extends: cc.Component,

    properties: {
        blockView: {
            type: cc.Object,
            default: null,
        },
        // custom data property
        // 格子视图
        cellViews: {
            type: cc.Object,
            default: null,
        },
        controller: {
            type: cc.Object,
            default: null,
        },
        gameModel: {
            type: cc.Object,
            default: null,
        },
    },

    // LIFE-CYCLE CALLBACKS:
    //
    // onLoad () {
    //     this.setLister();
    // },

    start () {

    },

    initWithModel(controller, gameModel) {
        this.gameModel = gameModel;
        this.controller = controller;
        if(this.cellViews) {
            for (let i=1; i <= g.PHASE_ROW; i++) {
                for (let j=1; j <= g.PHASE_COL; j++){
                    this.cellViews[i][j].node.destroy();
                }
            }
        }
        const blockView = this.getComponent("blockView");
        this.cellViews = blockView.initWithModel(gameModel.cells, g.PHASE_WIDTH, g.PHASE_HEIGHT, g.PHASE_ROW, g.PHASE_COL);
        this.blockView = blockView;
        this.setListener();
    },

    // 监听点击
    setListener: function () {
        const onSuccess = function (cellPos) {
            this.gameModel.selectCell(cellPos.x, cellPos.y);
            this.controller.updateView();
        }.bind(this);
        this.blockView.setListener(onSuccess);
    },

    updateView(cells) {
        for (const cell of cells) {
            this.cellViews[cell.x][cell.y].performAction();
        }
    },

    // 一段时间内禁止操作，不需要通过动画播放完后的动作回调
    disableTouch(dt) {
        if (dt <= 0) {
            return ;
        }
        this.blockView.isPlaying = true;
        this.blockView.node.runAction(cc.sequence(cc.delayTime(dt), cc.callFunc(function () {
            this.isPlaying = false;
        }, this.blockView)))
    },



});
